package com.sbpm.crmbpm.server.dao.impl;

import com.sbpm.crmbpm.server.dao.UserDao;
import com.sbpm.crmbpm.server.exceptions.ObjectNotFoundException;
import com.sbpm.crmbpm.shared.data.organisation.Role;
import com.sbpm.crmbpm.shared.data.organisation.User;
import org.kie.internal.task.api.UserGroupCallback;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.persistence.EntityManager;
import java.util.ArrayList;
import java.util.List;

@Component
public class UserDaoImpl implements UserDao
{

//    @Autowired
    private EntityManager em;

    public List<Role> getRolesForUser( String userId )
    {
        return em.createQuery( "select r from Role r join r.users ur where ur.isActive = true and ur.userId = :userId" )
                .setParameter( "userId", userId )
                .getResultList();
    }

    public User findActiveUserById( String id ) throws ObjectNotFoundException
    {
        List<User> users = em.createQuery( "select u from User u where u.userId = :id and u.isActive = true" )
                .setParameter( "id", id ).getResultList();
        if( users.size() == 0 )
        {
            throw new ObjectNotFoundException( "userid = " + id );
        }
        return users.get( 0 );
    }

    public Role findRoleById( String id ) throws ObjectNotFoundException
    {
        List<Role> roles = em.createQuery( "select r from Role r where r.roleId = :id" )
                .setParameter( "id", id ).getResultList();
        if( roles.size() == 0 )
        {
            throw new ObjectNotFoundException( "roleId = " + id );
        }
        return roles.get( 0 );
    }
}
